package net.projecteuler.util;

public class DigitUtil {
	public static int[] digits(int value, int base, boolean reverse){
		if(value < 0 || base < 2) return null;
		if(value == 0) return new int[]{0};
		
		int digitCnt = 0;
		for(int temp = value; temp > 0; temp /= base)
			digitCnt++;
		
		int[] result = new int[digitCnt];
		if(!reverse){
			for(int i = 0; i < digitCnt; i++){
				result[i] = value % base;
				value /= base;
			}
		} else {
			for(int i = digitCnt - 1; i >= 0; i--){
				result[i] = value % base;
				value /= base;
			}
		}
		
		return result;
	}
	
	public static int[] digits(int value){
		return digits(value, 10, false);
	}
	
	public static int value(int[] digits, int base, boolean reverse){
		if(digits == null || digits.length == 0 || base < 2) return 0;
		
		int result = 0;
		if(reverse){
			for(int i = 0; i < digits.length; i++){
				result = result * base + digits[i];
			}
		} else {
			for(int i = digits.length - 1; i >= 0; i--){
				result = result * base + digits[i];
			}
		}
		
		return result;
	}
	
	public static int value(int[] digits){
		return value(digits, 10, false);
	}
}
